package moodish.test;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Random;

import junit.framework.Assert;

import moodish.dummy.comm.client.ClientCommDummy;
import moodish.dummy.comm.server.ServerCommDummy;

import org.junit.Test;


public class ClientCommDummyTestCase {

	public static final String UNKNOWN = "unknown nickname";
	public static final String ERRROR = "ERROR";
	public final static String DEF_HOST = "localhost";
	public final static String DEF_NICKNAME_CLIENT_1 = "My Nickname 1";
	private Random random = new Random();

	private int generateRandomPort() {
		return random.nextInt(ServerCommDummy.MAX_PORT_NUMBER) + ServerCommDummy.MIN_PORT_NUMBER;
	}
	
	private void sleep(){
		try {
			Thread.sleep(100);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	@Test
	public void recievedMessages() {
		int randomPort = generateRandomPort();
		
		ServerCommDummy server = new ServerCommDummy(randomPort);
		server.start();
		
		sleep();
		
		ClientCommDummy client = new ClientCommDummy(randomPort);
		try {
			client.connect(DEF_HOST, DEF_NICKNAME_CLIENT_1);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		sleep();
		Assert.assertTrue(server.clientIsConnected(DEF_NICKNAME_CLIENT_1));
		Assert.assertTrue(client.isConnected());
		
		server.sendAcknowledge(DEF_NICKNAME_CLIENT_1);
		server.disconnectClient(DEF_NICKNAME_CLIENT_1);
		
		sleep();
		Assert.assertFalse(server.clientIsConnected(DEF_NICKNAME_CLIENT_1));
		Assert.assertFalse(client.isConnected());
	}
	
	@Test
	public void getNextMessageTest() {
		int randomPort = generateRandomPort();
		final ClientCommDummy client = new ClientCommDummy(randomPort);
		
		Thread thread = new Thread(new Runnable() {
			@Override
			public void run() {
				client.getNextMessage();
			}
		});

		thread.start();
		thread.interrupt();
	}
	
}
